﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.LinqBuilder;
using Microsoft.EntityFrameworkCore;
using Queer.Entity;
using Queer.IService.OrganizationManage;
using Queer.Model.Param.OrganizationManage;
using Queer.Util;
using Queer.Util.Helper;
using Queer.Util.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Queer.Service.OrganizationManage
{
    /// <summary>
    /// 创 建：
    /// 日 期：2021-04-07 16:44
    /// 描 述：机构管理服务类
    /// </summary>

    public class OrganizationsService : IOrganizationsService, ITransient
    {
        private readonly IRepository<OrganizationsEntity> _organizationsDB;
        private readonly IRepository<DataDictEntity> _dataDictEntityDB;
        private readonly IRepository<DataDictDetailEntity> _dataDictDetailEntityDB;

        public OrganizationsService(IRepository<DataDictEntity> dataDictEntity, IRepository<DataDictDetailEntity> dataDictDetailEntity, IRepository<OrganizationsEntity> organizationsDB)
        {
            _organizationsDB = organizationsDB;
            _dataDictEntityDB = dataDictEntity;
            _dataDictDetailEntityDB = dataDictDetailEntity;
        }

        #region 获取数据

        /// <summary>
        /// 带条件查询所有
        /// </summary>
        public async Task<List<OrganizationsEntity>> GetList(OrganizationsListParam param)
        {
            IQueryable<OrganizationsEntity> query = ListFilter(param);
            var data = await query.ToListAsync();
            return data;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        public async Task<List<OrganizationsEntity>> GetPageList(OrganizationsListParam param, Pagination pagination)
        {
            IQueryable<OrganizationsEntity> query = ListFilter(param);
            query = from org in query
                    join TitleType in _dataDictDetailEntityDB.AsQueryable() on org.OrganizationLevel equals TitleType.DictKey into resultsD
                    from TitleType in resultsD.DefaultIfEmpty()
                    join TitleData in _dataDictEntityDB.AsQueryable() on TitleType.DictType equals TitleData.DictType into results2
                    from TitleData in results2.DefaultIfEmpty()
                    where org.IsDelete == false && TitleType.DictStatus == 1 && TitleType.IsDelete == false && TitleData.IsDelete == false && TitleData.DictType.Equals("OrganizationLevel")
                    select new OrganizationsEntity
                    {
                        Id = org.Id,
                        Name = org.Name,
                        Code = org.Code,
                        OrganizationLevel = org.OrganizationLevel,
                        OrganizationType = org.OrganizationType,
                        LoginName = org.LoginName,
                        LoginPass = org.LoginPass,
                        Address = org.Address,
                        BelongArea = org.BelongArea,
                        ServiceElderlyCount = org.ServiceElderlyCount,
                        OrganizationLevelName = TitleType.DictValue,

                        CreateTime = org.CreateTime

                    };
            var data = await query.OrderByDescending(a => a.Id).ToPagedListAsync(pagination.PageIndex, pagination.PageSize);

            // 分页参数赋值
            pagination.TotalCount = data.TotalCount;
            return data.Items.ToList();
        }

        /// <summary>
        /// 根据ID获取对象
        /// </summary>
        public async Task<OrganizationsEntity> GetEntity(long id)
        {
            var data = await _organizationsDB.AsQueryable(p => p.Id == id).FirstOrDefaultAsync();
            return data;
        }

        /// <summary>
        /// 查询多个ID主键数据
        /// </summary>
        public async Task<List<OrganizationsEntity>> GetListByIds(string ids)
        {
            if (ids.IsNullOrEmpty())
                throw new Exception("参数不合法！");

            var idArr = TextHelper.SplitToArray<long>(ids, ',').ToList();
            var data = await _organizationsDB.AsQueryable(a => idArr.Contains(a.Id.GetValueOrDefault())).ToListAsync();

            return data;
        }

        #endregion

        #region 提交数据

        public async Task SaveForm(OrganizationsEntity entity)
        {
            if (entity.Id.IsNullOrZero())
            {
                // 默认赋值
                entity.Id = IdGeneratorHelper.Instance.GetId();
                await _organizationsDB.InsertNowAsync(entity);
            }
            else
            {
                await _organizationsDB.UpdateNowAsync(entity, ignoreNullValues: true);
            }
        }

        public async Task DeleteForm(string ids)
        {
            if (string.IsNullOrWhiteSpace(ids))
                throw new Exception("参数不合法！");

            var _ids = ids.Split(",");
            await _organizationsDB.BatchFakeDeleteAsync(_ids);
        }

        #endregion

        #region 私有方法
        private IQueryable<OrganizationsEntity> ListFilter(OrganizationsListParam param)
        {
            IQueryable<OrganizationsEntity> query = _organizationsDB.AsQueryable();
            if (param != null)
            {
                // 机构名称
                if (!string.IsNullOrEmpty(param.Name))
                    query = query.Where(p => p.Name.Contains(param.Name));
                // 机构类型（0居家养老1机构养老）
                if (param.OrganizationType.HasValue)
                    query = query.Where(p => p.OrganizationType == param.OrganizationType);
                // 机构等级
                if (param.OrganizationLevel.HasValue)
                    query = query.Where(p => p.OrganizationLevel == param.OrganizationLevel);

            }

            query = query.Where(a => a.IsDelete != true);

            return query;
        }

        #endregion
    }
}